<template>
  <div class="create-contest-container">
    <a-card class="create-card">
      <template #title>
        <div class="card-title"><icon-plus /> 创建竞赛</div>
      </template>

      <a-form :model="formData" layout="vertical">
        <!-- 基本信息部分 -->
        <a-divider>基本信息</a-divider>
        <a-form-item field="title" label="竞赛标题" required>
          <a-input v-model="formData.title" placeholder="请输入竞赛标题" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="startTime" label="开始时间" required>
              <a-date-picker
                v-model="formData.startTime"
                show-time
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="duration" label="竞赛时长(分钟)" required>
              <a-input-number
                v-model="formData.duration"
                :min="1"
                :max="1440"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 新增：限制参赛人数 -->
        <a-form-item field="participantLimit" label="参赛人数限制" required>
          <a-input-number
            v-model="formData.participantLimit"
            :min="1"
            style="width: 100%"
            placeholder="请输入参赛人数限制"
          />
        </a-form-item>
        <a-form-item field="description" label="竞赛描述">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入竞赛描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>

        <a-form-item field="coverImage" label="竞赛封面">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :custom-request="handleUpload"
            :limit="1"
            @progress="handleProgress"
          >
            <template #upload-button>
              <div
                class="upload-button"
                :class="{ 'has-image': fileList.length }"
              >
                <template v-if="!fileList.length">
                  <div class="upload-icon">
                    <icon-plus />
                  </div>
                  <div class="upload-text">点击上传封面</div>
                  <div class="upload-hint">建议尺寸 1200x400px</div>
                </template>
                <div v-else class="preview-wrapper">
                  <img
                    :src="fileList[0].url"
                    alt="封面预览"
                    class="preview-image"
                  />
                  <div class="progress-overlay" v-if="uploading">
                    <a-progress
                      :percent="progressPercent"
                      type="circle"
                      size="mini"
                      :stroke-width="10"
                      status="success"
                    />
                  </div>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>

        <!-- 题目管理部分 -->
        <a-divider>题目管理</a-divider>
        <div class="total-score">
          <span class="score-label">当前总分：</span>
          <span class="score-value">{{ totalScore }}</span>
        </div>

        <div
          v-for="(question, index) in formData.questions"
          :key="index"
          class="question-item"
        >
          <div class="question-header">
            <h3>题目 {{ index + 1 }}</h3>
            <a-button
              type="text"
              status="danger"
              @click="removeQuestion(index)"
              v-if="(formData?.questions || []).length > 1"
            >
              <icon-delete />删除
            </a-button>
          </div>
          <!-- 新增分值输入 -->
          <a-form-item
            :field="`questions[${index}].score`"
            label="题目分值"
            required
          >
            <a-input-number
              v-model="question.score"
              :min="1"
              :precision="0"
              placeholder="请输入题目分值"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item
            :field="`questions[${index}].title`"
            label="题目标题"
            required
          >
            <a-input v-model="question.title" placeholder="请输入题目标题" />
          </a-form-item>

          <a-form-item
            :field="`questions[${index}].content`"
            label="题目内容"
            required
          >
            <a-textarea
              v-model="question.content"
              placeholder="请输入题目内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>

          <!-- 新增限制设置 -->
          <div class="constraints">
            <a-form-item
              :field="`questions[${index}].timeLimit`"
              label="时间限制 (毫秒)"
              required
            >
              <a-input-number
                v-model="question.timeLimit"
                :min="1"
                style="width: 100%"
                placeholder="请输入时间限制，单位毫秒"
              />
            </a-form-item>
            <a-form-item
              :field="`questions[${index}].stackLimit`"
              label="堆栈限制 (B)"
              required
            >
              <a-input-number
                v-model="question.stackLimit"
                :min="1"
                style="width: 100%"
                placeholder="请输入堆栈限制，单位B"
              />
            </a-form-item>
            <a-form-item
              :field="`questions[${index}].memoryLimit`"
              label="内存限制 (B)"
              required
            >
              <a-input-number
                v-model="question.memoryLimit"
                :min="1"
                style="width: 100%"
                placeholder="请输入内存限制，单位B"
              />
            </a-form-item>
          </div>

          <!-- 测试用例部分 -->
          <div class="test-cases">
            <div class="test-cases-header">
              <h4>测试用例</h4>
              <a-button type="text" @click="addTestCase(index)">
                <icon-plus />添加用例
              </a-button>
            </div>

            <div
              v-for="(testCase, caseIndex) in question.testCases"
              :key="caseIndex"
              class="test-case-item"
            >
              <div class="test-case-header">
                <span>用例 {{ caseIndex + 1 }}</span>
                <a-button
                  type="text"
                  status="danger"
                  @click="removeTestCase(index, caseIndex)"
                  v-if="(question.testCases || []).length > 1"
                >
                  <icon-delete />
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="输入">
                    <a-textarea
                      v-model="testCase.input"
                      placeholder="请输入测试用例输入"
                      :auto-size="{ minRows: 2, maxRows: 4 }"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="预期输出">
                    <a-textarea
                      v-model="testCase.output"
                      placeholder="请输入预期输出"
                      :auto-size="{ minRows: 2, maxRows: 4 }"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </div>
        </div>

        <div class="add-question">
          <a-button type="dashed" long @click="addQuestion">
            <icon-plus />添加题目
          </a-button>
        </div>

        <div class="form-actions">
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" @click="handleSubmit">创建竞赛</a-button>
          </a-space>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { IconPlus, IconDelete } from "@arco-design/web-vue/es/icon";
import { CompetitionControllerService } from "../../../generatedCom/services/CompetitionControllerService";
import { CompetitionAddRequest } from "../../../generatedCom/models/CompetitionAddRequest";
import CodeEditor from "@/components/CodeEditor.vue";
import { useStore } from "vuex";
import axios from "axios";
const store = useStore();
const router = useRouter();

// 文件列表
interface FileItem {
  uid: any;
  name: string;
  url: string;
}

const fileList = ref<FileItem[]>([]);
// 表单数据
const formData = reactive({
  title: "",
  startTime: undefined,
  duration: 90,
  description: "",
  coverImage: "",
  participantLimit: 100,
  totalScore: 0,
  questions: [
    {
      title: "",
      content: "",
      // 新增题目限制默认值
      timeLimit: 1, // 默认1秒
      stackLimit: 256, // 默认256KB
      memoryLimit: 128, // 默认128MB
      score: undefined, // 新增分值字段
      testCases: [
        {
          input: "",
          output: "",
        },
      ],
    },
  ],
});
// 计算总分
const totalScore = computed(() => {
  return formData.questions?.reduce((sum, q) => sum + (q.score || 0), 0) || 0;
});
// 添加题目
const addQuestion = () => {
  formData.questions?.push({
    title: "",
    content: "",
    timeLimit: 1,
    stackLimit: 256,
    memoryLimit: 128,
    score: undefined,
    testCases: [
      {
        input: "",
        output: "",
      },
    ],
  });
};

// 删除题目
const removeQuestion = (index: number) => {
  formData.questions?.splice(index, 1);
};

// 添加测试用例
const addTestCase = (questionIndex: number) => {
  formData.questions?.[questionIndex]?.testCases?.push({
    input: "",
    output: "",
  });
};

// 删除测试用例
const removeTestCase = (questionIndex: number, caseIndex: number) => {
  formData.questions?.[questionIndex]?.testCases?.splice(caseIndex, 1);
};

// 在 script setup 部分添加上传相关的状态
const uploading = ref(false);
const progressPercent = ref(0);

// 处理上传进度
const handleProgress = (event: any) => {
  progressPercent.value = Math.round((event.loaded / event.total) * 100);
};

// 修改图片上传处理函数
const handleUpload = async (option: any) => {
  const { onProgress, onSuccess, onError, fileItem } = option;
  uploading.value = true;
  try {
    const formDataTemp = new FormData();
    formDataTemp.append("biz", "contest_cover");
    formDataTemp.append("file", fileItem.file, fileItem.file.name);

    const response = await uploadFileUsingPost(formDataTemp);

    // 更新 fileList
    fileList.value = [
      {
        uid: fileItem.uid,
        name: fileItem.file.name,
        url: response.data.data, // 使用返回的图片URL
      },
    ];

    formData.coverImage = response.data.data;
    onSuccess(response);
    Message.success("上传成功");
  } catch (error) {
    onError(error);
    Message.error("上传失败");
  } finally {
    uploading.value = false;
    progressPercent.value = 0;
  }
};

const uploadFileUsingPost = async (formData: any) => {
  console.log(store.state.user.token);
  return axios.post("http://localhost:8101/api/user/user/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data", // 确保设置正确的 Content-Type
      Authorization: store.state.user.token, // 添加 Authorization 头
    },
    withCredentials: true,
  });
};
// 提交表单
const handleSubmit = async () => {
  try {
    // 这里添加表单验证和提交逻辑
    console.log(formData);
    formData.totalScore = totalScore.value;
    const res = await CompetitionControllerService.publishUsingPost(
      formData as CompetitionAddRequest
    );
    console.log(res);

    Message.success("竞赛创建成功");
    // router.push("/contest");
  } catch (error) {
    Message.error("创建失败");
  }
};

// 取消创建
const handleCancel = () => {
  router.back();
};
</script>

<style scoped>
/* 新增总分样式 */
.total-score {
  margin: 16px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: right;
  font-size: 16px;
}

.score-label {
  color: #666;
}

.score-value {
  font-weight: 600;
  color: var(--color-primary);
  margin-left: 8px;
}

/* 调整题目分值输入框样式 */
:deep(.arco-input-number) {
  width: 100%;
}
.create-contest-container {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 20px;
}

.create-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.question-item {
  margin-bottom: 32px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

/* 限制项样式 */
.constraints {
  margin-top: 16px;
  padding: 16px;
  background: #f1f7fd;
  border-left: 4px solid var(--color-primary);
  border-radius: 8px;
}

.test-cases {
  margin-top: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.test-cases-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.test-case-item {
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.test-case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.add-question {
  margin: 24px 0;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

.upload-button {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}
:deep(.arco-upload-list-picture-card) {
  margin: 0;
}

.upload-button {
  width: 100%;
  height: 160px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 2px dashed #e9ecef;
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.upload-button:hover {
  border-color: var(--color-primary);
  background: #f3f9ff;
}

.upload-icon {
  font-size: 24px;
  color: var(--color-primary);
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
  color: #495057;
  font-weight: 500;
}

.upload-hint {
  font-size: 12px;
  color: #868e96;
  margin-top: 4px;
}

.preview-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.progress-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 其他样式优化 */
.question-item {
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.question-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.constraints {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-top: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.test-case-item {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.test-case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.add-question {
  margin: 24px 0;
}

.form-actions {
  margin-top: 32px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .constraints {
    grid-template-columns: 1fr;
  }
  .a-col {
    width: 100%;
    margin-bottom: 16px;
  }
}
</style>
